#include "inputwidgetutils.h"
#include <QLineEdit>
#include <QSpinBox>
#include <QComboBox>
InputWidgetUtils::InputWidgetUtils(QObject *parent)
    : QObject{parent}
{}

QWidget *InputWidgetUtils::createInputWidget(QFieldAttribute fieldAttribute)
{
    QWidget* inputWidget = nullptr;
    switch(fieldAttribute.fieldType){
    case QFieldAttribute::TEXT:
        inputWidget = new QLineEdit();
        ((QLineEdit*)inputWidget)->setText(fieldAttribute.value);
        break;
    case QFieldAttribute::BUMBER:
        inputWidget = new QSpinBox();
        break;
    case QFieldAttribute::COMBOBOX:
        inputWidget = new QComboBox();
        QStringList  values = fieldAttribute.value.split("|");
        for(auto item :values){
            if(item.isEmpty()){
                continue;
            }
            QStringList value_key = item.split(":");
            if(value_key.size() == 2){
                ((QComboBox*)inputWidget)->addItem(value_key.at(0),value_key.at(1));
            }
        }
        break;
    };
    inputWidget->setProperty("fieldType",fieldAttribute.fieldType);
    inputWidget->setProperty("fieldName",fieldAttribute.fieldName);
    return inputWidget;
}

QWidget *InputWidgetUtils::createSreachWidget(QFieldAttribute fieldAttribute)
{
    QWidget* sreachWidget = nullptr;
    switch(fieldAttribute.fieldType){
    case QFieldAttribute::TEXT:
        sreachWidget = new QLineEdit();
        ((QLineEdit*)sreachWidget)->setText(fieldAttribute.value);
        break;
    case QFieldAttribute::COMBOBOX:
        sreachWidget = new QComboBox();
        QStringList  values = fieldAttribute.value.split("|");
        if(values.size() !=0 && !values.at(0).isEmpty()){
            ((QComboBox*)sreachWidget)->addItem(tr("--ALL--"),"");
        }
        for(auto item :values){
            if(item.isEmpty()){
                continue;
            }
            QStringList value_key = item.split(":");
            if(value_key.size() == 2){
                ((QComboBox*)sreachWidget)->addItem(value_key.at(0),value_key.at(1));
            }
        }
        break;
    };
    if(nullptr == sreachWidget){
        return nullptr;
    }
    sreachWidget->setProperty("fieldType",fieldAttribute.fieldType);
    sreachWidget->setProperty("fieldName",fieldAttribute.fieldName);
    return sreachWidget;
}

QString InputWidgetUtils::getInputWidgetValue(QWidget *inputWidget)
{
    QString value = "";
    if(nullptr == inputWidget){
        return value;
    }
    QFieldAttribute::FieldType fieldType = (QFieldAttribute::FieldType ) inputWidget->property("fieldType").toInt();
    switch(fieldType)   {
    case QFieldAttribute::TEXT:
        return ((QLineEdit*)inputWidget)->text() ;
    case QFieldAttribute::BUMBER:
        return QString::number(((QSpinBox*)inputWidget)->value()) ;
    case QFieldAttribute::COMBOBOX:
        return ((QComboBox*)inputWidget)->currentData().toString() ;
    }
    return value;
}
